﻿<?php

include 'webSocket.php';

class WebSocket2 extends WebSocket{
    public function run(){
        while(true){
            $socketArr = $this->sockets;
            $write = NULL;
            $except = NULL;
            socket_select($socketArr, $write, $except, NULL);
            foreach ($socketArr as $socket){
                if ($socket == $this->master){
                    $client = socket_accept($this->master);
                    if ($client < 0){
                        $this->log("socket_accept() failed");
                        continue;
                    }else{
                        $this->connect($client);
                    }
                }
                else{
                    $this->log("----------New Frame Start-------");
                    $bytes = @socket_recv($socket,$buffer,2048,0);
                    if ($bytes == 0){
                        $this->disconnect($socket);
                    }else{
                        $user = $this->getUserBySocket($socket);
                        if (!$user->handshake){
                            $this->doHandShake($user, $buffer);
                        }else{
                            $buffer = $this->unwrap($user->socket, $buffer);

                            //请求为stock时，向通道内推送数据
                            if ($buffer == 'stock') {
                                $arr = array();

                                //模拟数据
                                for ($i=0; $i < 6; $i++) {
                                    $arr[] = rand(1, 100) / 100;
                                }

                                $this->send($user->socket, json_encode($arr));
                            }
                        }
                    }
                }
            }
        }
    }
}

$s = new WebSocket2('localhost',443);
$s -> run();

